<template>
  <view class="chooseAddressee">
    <u-navbar :is-back="false" title="" :border-bottom="false">
      <view class="slot-wrap" :class="downStatus ? 'down-open':'down-close'">
        <view class="btn-box" @click="onClickBack">
          <view class="icon">
            <u-icon name="nav-back" color="#606266" size="44"></u-icon>
          </view>
        </view>
        <view class="center">
          <u-dropdown active-color="#FBD321" @open="downStatus = true" @close="downStatus = false" title-size="36">
            <u-dropdown-item v-model="value1" title="选择收信人" :options="options1" v-if="timUserInfo.isService" @change="storeTypeChange"></u-dropdown-item>
            <u-dropdown-item v-model="value1" title="选择收信人" :options="options2" v-else @change="storeTypeChange"></u-dropdown-item>
          </u-dropdown>
        </view>
        <view class="btn-box">
          <view style="icon">
            <u-icon name="nav-back" color="#fff" size="44"></u-icon>
          </view>
        </view>
      </view>
    </u-navbar>
    
    <!-- 搜索 -->
    <view class="search">
      <u-search placeholder="搜索联系人" v-model="keyword" :animation="true" @search="onSearch" @clear="onClear"></u-search>
    </view>
    
    <!-- 用户列表 -->
    <view class="user-list-box selected">
      <scroll-view class="scroll" scroll-y v-if="contacts.length > 0" :scroll-into-view="anchor">
        <view class="item" v-for="(item, index) in contacts" :key="index" :id="`anchor-${item.letter}`">
          <view class="index-anchor"><text>{{item.letter}}</text></view>
          <view class="index-item">
            <view class="children-item" v-for="(i, k) in item.contacts" :key="k" @click="onChangeItem(index, k)">
              <view class="radio" :class="{active: i.selected}">
                <u-icon name="checkmark" color="#fff" size="28"></u-icon>
              </view>
              <view class="user flex flex-ai-c">
                <view class="group-avatar" v-if="i.type === 'GROUP'">
                  <text>群</text>
                </view>
                <image v-else class="avatar" :src="i.headImg"></image>
                <view class="info flex flex-ai-c">
                  <text>{{i.type === 'GROUP' ? i.group_name : i.userName}}</text>
                  <block v-if="i.type !== 'GROUP'">
                    <image v-if="i.isPartner" class="badge" src="https://files.yzsheng.com/client/order/hehuorenicon.png"></image>
                    <image v-else class="badge" src="https://files.yzsheng.com/client/me/img/hehuoren2.png"></image>
                    <image v-if="i.isOwner" class="badge" src="https://files.yzsheng.com/client/order/chebiao.png"></image>
                    <view class="consume-status" :class="{not: !i.isCostMoney}"><text>{{i.isCostMoney ? '已消费' : '未消费'}}</text></view>
                  </block>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
        
      <view class="index-bar" v-if="indexList.length > 1" @touchstart.stop.prevent="onTouchMove" @touchmove.stop.prevent="onTouchMove">
        <text class="text" v-for="(item, index) in indexList" :key="index" :data-index="index">{{item}}</text>
      </view>
    </view>
    
    <!-- 下一步操作 -->
    <view class="footer" v-show="selected.length > 0" @click="onClickNext">
      <view class="btn-box">
        <view class="btn flex flex-ai-c flex-jc-c">
          <text class="text">下一步</text>
        </view>
      </view>
    </view>
      
    </view>
  </view>
</template>

<script>
import timLogin from '@/utils/timLogin.js' // 导入tim 登录
import pinyin from '@/utils/pinyin/pinyinMass.js'
export default {
  data() {
    return {
      value1: 1,
      options1: [{
        label: '全部',
        value: 1,
      },
      {
        label: '已消费',
        value: 2,
      },
      {
        label: '未消费',
        value: 3,
      },
      {
        label: '群',
        value: 4,
      },
      {
        label: '合伙人',
        value: 5,
      },
      {
        label: '企业员工',
        value: 6,
      }],
      options2: [{
        label: '全部',
        value: 1,
      },
      {
        label: '已消费',
        value: 2,
      },
      {
        label: '未消费',
        value: 3,
      },
      {
        label: '群',
        value: 4,
      }],
      downStatus: false,
      anchor: 'anchor-A', // 列表锚点
      indexList: [],
      keyword: '' ,// 搜索关键词
      sidebar: {},
      groupList: [],
      result: {
        PageIndex: 1,
        PageSize: 20,
        isCostMoney: -1,
        accountType: -1,
        isEnd: false,
        loading: false,
        status: 'loading',
        data: []
      },
      contacts: [], // 好友列表
      selected: [] , // 已选好友
    }
  },
  computed: {
    timUserInfo() {
      return this.$store.state.timUserInfo
    }
  },
  onLoad() {
    // 获得右侧index-bar 布局信息
    this.$nextTick(() => {
      this.$uGetRect('.index-bar').then(rect => {
      	this.sidebar = {
      		height: rect.height,
      		top: rect.top
      	}
      });
    })
    
    uni.showLoading({
      title: '加载中'
    })
    // 登录tim
    if(this.$store.state.isSDKReady) {
      this.getFriendList()
    } else {
      timLogin(() => {
        this.getFriendList()
      })
    }
  },
  methods: {
    // 点击返回
    onClickBack() {
      uni.navigateBack({
        delta: 1
      })
    },
    onTouchMove(event) {
      const sidebarLength = this.indexList.length;
      const touch = event.touches[0];
      const itemHeight = this.sidebar.height / sidebarLength;
      let clientY = 0;
      clientY = touch.clientY;
      let index = Math.floor((clientY - this.sidebar.top) / itemHeight);
      if (index < 0) {
      	index = 0;
      } else if (index > sidebarLength - 1) {
      	index = sidebarLength - 1;
      }
      this.anchor = 'anchor-' + this.indexList[index]
    },
    // 获取好友列表
    async getFriendList(data = {}, type) {
      let isService = this.$store.state.timUserInfo.isService //是否是服务商
      uni.showLoading({
        title: '加载中'
      })
      try{
        // 群
        let group = []
        if(this.groupList.length <= 0) {
          let groupRes = isService ? await this.$api.chat.GetServiceProvidersIMGroup({
            in_Group_Type: 10,
            userId: this.$store.state.timUserInfo.userId
          }) : await this.$api.chat.GetUserServiceProvider()
          if(isService) {
            groupRes.data = groupRes.data.map((item, index) => {
              item.type = 'GROUP'
              return item
            })
            group = groupRes.data
            this.groupList = groupRes.data
          } else {
            delete groupRes.data.parentUser
            delete groupRes.data.serviceProvider
            if(groupRes.data.myIMGroup) {
              groupRes.data.myIMGroup = groupRes.data.myIMGroup.map(item => {
                item.type = 'GROUP'
                return item
              })
            } else {
              groupRes.data.myIMGroup = []
            }
            if(groupRes.data.parentIMGroup) {
              groupRes.data.parentIMGroup.type = 'GROUP'
            } else {
              delete groupRes.data.parentIMGroup
            }
            group = [...groupRes.data.myIMGroup, groupRes.data.parentIMGroup]
            this.groupList = [...groupRes.data.myIMGroup, groupRes.data.parentIMGroup]
          }

        } else {
          group = this.groupList
        }
        
        // 好友
        let res = {data: []}
        if(!type) {
          res = await this.$api.chat.GetMyPartnerList({
            pageIndex: this.result.PageIndex,
            pageSize: this.result.PageSize,
            keyWords: this.keyword,
            isCostMoney: -1,
            accountType: -1,
            ...data,
          })
          this.result = res.data
        }
        
        let list = res.data.concat(group)
        this.initialOrder(list)
        uni.hideLoading()
      }catch(e){
        uni.hideLoading()
      }
    },
    // 根据名称首字母进行排序
    initialOrder(list) {
      this.contacts = pinyin.paixu(list)
      this.contacts.sort(function(o1, o2) {
        return o1.letter.charCodeAt(0) - o2.letter.charCodeAt(0)
      })
      this.indexList = this.contacts.map(item => {
        return item.letter
      })
    },
    // 点击联系人
    onChangeItem(parent, current) {
      let list = this.contacts
      let select = []
      list[parent].contacts[current].selected = !list[parent].contacts[current].selected
      this.contacts = list
      list.map(item => {
        item.contacts.map(i => {
          if(i.selected) {
            select.push({
              id: i.type === 'GROUP' ? i.id : i.uid,
              name: i.type === 'GROUP' ? i.group_name : i.userName,
              type:  i.type || 'C2C'
            })
          }
        })
      })
      this.selected = select
    },
    // 点击下一步
    onClickNext() {
      this.$store.commit('massTempData', this.selected)
      uni.redirectTo({
        url: '/pages_chat/chat/chat?id=&type=MASS'
      })
    },
    // 条件筛选
    storeTypeChange(data) {
      if(data === 4) {
        this.getFriendList({}, true)
      }
      if(data === 1) {
        this.getFriendList({})
      }
      if(data === 2) {
        this.getFriendList({
          isCostMoney: 1
        })
      }
      if(data === 3) {
        this.getFriendList({
          isCostMoney: 0
        })
      }
      if(data === 5) {
        this.getFriendList({
          accountType: 1
        })
      }
      if(data === 6) {
        this.getFriendList({
          accountType: 4
        })
      }
    },
    // 点击搜索
    onSearch() {
      if(!this.keyword) return false
      this.getFriendList({
        keyWords: this.keyword
      })
    },
    // 点击搜索框清楚
    onClear() {
      this.getFriendList({})
    }
  }
}
</script>

<style lang="scss">
page{
  height: 100vh;
}
.chooseAddressee{
  height: 100%;
  display: flex;
  flex-direction: column;
  .slot-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 1;
    position: relative;
    .btn-box{
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 14rpx 14rpx 14rpx 24rpx;
      .icon{
        width: 44rpx;
        height: auto;
      }
    }
    /deep/ .u-dropdown__menu__item__text{
      color: #333 !important;
      margin-right: 18rpx;
    }
    /deep/ .uicon-arrow-down-fill{
      color: #666 !important;
      font-size: 22rpx !important;
    }
    /deep/ .u-dropdown__content__popup .uni-scroll-view{
      border-radius: 0 0 20rpx 20rpx;
    }
    /deep/ .uicon-arrow-down-fill{
      font-size: 14rpx !important;
    }
    /deep/ .u-border-bottom{
      text-align: center;
      &::after{
        border-bottom: none;
      }
    }
    /deep/ .u-cell_title{
      width: 100% !important;
    }
    /deep/ .u-cell-item-box{
      padding: 10rpx 0;
    }
    /deep/ .u-dropdown-item__options .u-cell{
      padding: 10rpx 0;
    }
    // 下拉菜单打开时，给下拉菜单设置高度
    &.down-open {
      & /deep/ .u-dropdown__content {
        height: 100vh !important;
      }
    }
    &.down-close {
      & /deep/ .u-dropdown__content {
        height: 0 !important;
      }
    }
  }
  .search{
    background-color: #fff;
    padding: 10rpx 24rpx;
  }
  .user-list-box{
    flex: 1;
    background-color: #fff;
    overflow: hidden;
    position: relative;
    .checkbox-group{
      width: 100%;
    }
    .scroll{
      height: 100%;
      .item{
        .index-anchor{
          box-sizing: border-box;
          padding: 14rpx 24rpx;
          color: #606266;
          width: 100%;
          font-weight: 500;
          font-size: 28rpx;
          line-height: 1.2;
          background-color: #f5f5f5;
        }
        .index-item{
          .children-item{
            display: flex;
            align-items: center;
            padding: 0 25rpx;
            .radio{
              display: flex;
              align-items: center;
              justify-content: center;
              box-sizing: border-box;
              width: 44rpx;
              height: 44rpx;
              border-radius: 44rpx;
              border: 2rpx solid #d0d0d0;
              &.active{
                background: linear-gradient(0deg, #FBD220, #FFE23E);
                border: none;
              }
            }
            .user{
              margin-left: 40rpx;
              flex: 1;
              padding: 28rpx 0;
              border-top: 2rpx solid #eee;
              .avatar{
                width: 70rpx;
                height: 70rpx;
                border-radius: 70rpx;
              }
              .group-avatar{
                width: 70rpx;
                height: 70rpx;
                border-radius: 70rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #FED731;
                font-size: 32rpx;
                color: #3d3d3d;
              }
              .info{
                font-size: 32rpx;
                color: #333;
                margin-left: 25rpx;
                .badge{
                  height: 40rpx;
                  width: 40rpx;
                  margin-left: 15rpx;
                }
                .consume-status{
                  width: 90rpx;
                  height: 34rpx;
                  border: 2rpx solid #50B300;
                  border-radius: 17rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  font-size: 22rpx;
                  color: #55B507;
                  margin-left: 18rpx;
                  &.not{
                    border: 2rpx solid #D55000;
                    color: #D55000;
                  }
                }
              }
            }
            &:first-child{
              .user{
                border-top: none;
              }
            }
          }
        }
      }
    }
    .index-bar{
      display: flex;
      flex-direction: column;
      position: absolute;
      right: 14rpx;
      top: 50%;
      transform: translateY(-55%);
      font-size: 24rpx;
      text-align: center;
      background-color: #f7f7f7;
      padding: 20rpx 0;
      border-radius: 40rpx;
      .text{
        padding: 2rpx 16rpx;
      }
    }
    
  }
  .selected {
    padding-bottom: 120rpx;  
    padding-bottom: calc(constant(safe-area-inset-bottom) + 120rpx);  
    padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
  }
  .footer{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding-bottom: 0;  
    padding-bottom: constant(safe-area-inset-bottom);  
    padding-bottom: env(safe-area-inset-bottom);
    background-color: #fff;
    .btn-box{
      padding: 16rpx 24rpx;
      .btn{
        height: 88rpx;
        background: linear-gradient(0deg, #FBD220, #FFE23E);
        border-radius: 44rpx;
        .text{
          font-size: 32rpx;
          color: #333;
          margin-left: 16rpx;
        }
      }
    }
  }
  
}
</style>
